package com.thug.facade;

import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.thug.bo.Customer;
import com.thug.client.Product;
import com.thug.client.ProviderWs;
import com.thug.service.CustomerService;

public class CustomerFacade {

	private static final Log LOGGER = LogFactory.getLog(CustomerFacade.class);

	private CustomerService customerService;
	private ProviderWs webServices;

	public void setCustomerService(CustomerService customerService) {
		this.customerService = customerService;
	}

	public void setWebServices(ProviderWs webServices) {
		this.webServices = webServices;
	}

	public CustomerFacade() {
		LOGGER.debug("instantiation...");
	}

	public Customer getCustomer(int customerId) throws Exception {

		LOGGER.info("start - getCustomer");
		long startTime = System.currentTimeMillis();

		try {

			Customer customer = customerService.find(customerId);

			LOGGER.info("Calling Web Services...");
			List<Product> products = webServices.getProducts(customerId);
			LOGGER.info("Web Services called.");

			customer.setProducts(products);

			LOGGER.info("Getting lazy addresses...");
			customer.getAddresses().size();
			LOGGER.info("Lazy addresses got.");

			return customer;

		} finally {

			long endTime = System.currentTimeMillis();
			long durationTime = endTime - startTime;

			LOGGER.info("end (" + durationTime + "ms)");
		}
	}

	public void updateCustomerName(int customerId, String newLastName) throws Exception {

		LOGGER.info("start - updateCustomerName");
		long startTime = System.currentTimeMillis();

		try {

			Customer customer = customerService.find(customerId);

			LOGGER.info("Calling Web Services...");
			List<Product> products = webServices.getProducts(customerId);
			LOGGER.info("Web Services called.");

			customer.setProducts(products);

			LOGGER.info("Getting lazy addresses...");
			customer.getAddresses().size();
			LOGGER.info("Lazy addresses got.");

			LOGGER.info("Setting new last name...");
			customer.setLastName(newLastName);
			LOGGER.info("Last name set.");

			LOGGER.info("Updating customer...");
			customerService.update(customer);
			LOGGER.info("Customer updated.");

		} finally {

			long endTime = System.currentTimeMillis();
			long durationTime = endTime - startTime;

			LOGGER.info("end (" + durationTime + "ms)");
		}
	}
}
